<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="1024" @ok="handleSubmit">
    <BasicForm @register="registerForm" ref="formRef" />
    <!-- <a-tabs v-model:activeKey="activeFormKey" animated @change="handleChangeTabs" type="card">
      <a-tab-pane tab="基本信息" key="formBasicinformation" :forceRender="true">
        <BasicForm @register="registerBasicinformationForm" ref="formBasicinformationRef" style="height:300px" >
          <template #masterPlanSlot="{ model, field }">
            <a-input-search v-model:value="model[field]" placeholder="请选择MPS列表" @search="masterPlanOpen" />
          </template>
        </BasicForm>
      </a-tab-pane>
      <a-tab-pane tab="计划参数" key="formPlanParameter" :forceRender="true">
        <BasicForm @register="registerPlanParameterForm" ref="formPlanParameterRef" />
      </a-tab-pane>
      <a-tab-pane tab="供需" key="formSupplyDemand" :forceRender="true">
        <BasicForm @register="registerSupplyDemandForm" ref="formSupplyDemandRef" />
      </a-tab-pane>
      <a-tab-pane tab="优化" key="formOptimize" :forceRender="true">
        <BasicForm @register="registerOptimizeForm" ref="formOptimizeRef" />
      </a-tab-pane>
    </a-tabs> -->
    <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated @change="handleChangeTabs">
      <!-- <a-tab-pane tab="版本" key="psPlanOrderVersion" :forceRender="true">
        <JVxeTable keep-source resizable ref="psPlanOrderVersion"
          :loading="psPlanOrderVersionTable.loading" :columns="psPlanOrderVersionTable.columns"
          :dataSource="psPlanOrderVersionTable.dataSource" :height="340"
          rowSelection :disabled="formDisabled" :toolbar="true" />
      </a-tab-pane> -->
      <a-tab-pane tab="订单需求" key="psPlanOrderItem" :forceRender="true">
        <JVxeTable
          keep-source
          resizable
          ref="psPlanOrderItem"
          :loading="psPlanOrderItemTable.loading"
          :columns="psPlanOrderItemTable.columns"
          :dataSource="psPlanOrderItemTable.dataSource"
          :height="340"
          :rowSelection="true"
          :disabled="formDisabled"
          :toolbar="true"
        />
      </a-tab-pane>
      <a-tab-pane tab="MRP计算结果" key="psPlanOrderResult" :forceRender="true">
        <JVxeTable
          keep-source
          resizable
          ref="psPlanOrderResult"
          :loading="psPlanOrderResultTable.loading"
          :columns="psPlanOrderResultTable.columns"
          :dataSource="psPlanOrderResultTable.dataSource"
          :height="340"
          rowSelection
          @selectRowChange="handleSelectRowChange"
        >
          <template #toolbarAfter>
            <a-button type="primary" @click="handleRelease" v-if="hasPermission('ps:planOrder:release')">释放订单</a-button>
            <a-select
              v-model:value="activeFilterProp"
              :options="options"
              :size="size"
              placeholder="请选择过滤条件"
              style="width: 100px; margin-left: 10px"
              @change="filterProcurement"
            ></a-select>
            <a-button
              style="margin-left: 10px;"
              type="primary"
              @click="
                clickExport({
                  json: psPlanOrderResultTable.dataSource.map((item: any) => {
                    return {
                      rowNum: item.rowNum,
                      resultVersion: item.resultVersion,
                      materialCode: item.materialCode,
                      materialName: item.materialName,
                      spec: item.spec,
                      unitName: item.unitName,
                      supplyType: item.supplyType == 0 ? '自制' : item.supplyType == 1 ? '采购' : item.supplyType == 2 ? '委外' : '',
                      supplierName: item.supplierName,
                      orderQuantity: item.orderQuantity,
                      mrpQuantity: item.mrpQuantity,
                      adjustedMrpQuantity: item.adjustedMrpQuantity,
                      releaseQuantity: item.releaseQuantity,
                      demandDate: item.demandDate,
                      startDate: item.startDate,
                      demandType: item.demandType == 0 ? '独立' : item.demandType == 1 ? '相关' : '',
                      releaseStatus: item.releaseStatus == 0 ? '未释放' : item.demandType == 1 ? '已释放' : '',
                      productScheduleStatus: item.productScheduleStatus == 0 ? '否' : item.demandType == 1 ? '是' : '',
                      lockStatus: item.lockStatus == 0 ? '未锁定' : item.demandType == 1 ? '已锁定' : '',
                      orderRowNumber: item.orderRowNumber,
                      firstBillCode: item.firstBillCode,
                      remark: item.remark,
                    };
                  }),
                  name: 'MRP计算结果',
                  titleArr: [
                    '行号',
                    '版本号',
                    '料品编号',
                    '料品名称',
                    '料品规格',
                    '单位名称',
                    '供应类型',
                    '供应商名称',
                    '订单数量',
                    'MRP数量',
                    '调整后MRP数量',
                    '释放量',
                    '需求日期',
                    '开工日期',
                    '需求类型',
                    '释放状态',
                    '是否排产',
                    '锁定状态',
                    '来源行号',
                    '来源订单号',
                    '备注',
                  ],
                  sheetName: 'MRP计算结果',
                })
              "
              >导出</a-button
            >
            <!-- <a-button style="margin-left: 10px;" type="primary" @click="filterProcurement">{{ isProcurementStatus ? '取消过滤' : '过滤采购与自制'}}</a-button> -->
          </template>
        </JVxeTable>
      </a-tab-pane>
      <!-- <a-tab-pane tab="组织" key="psPlanOrderOrganization" :forceRender="true">
        <JVxeTable keep-source resizable ref="psPlanOrderOrganization"
          :loading="psPlanOrderOrganizationTable.loading"
          :columns="psPlanOrderOrganizationTable.columns"
          :dataSource="psPlanOrderOrganizationTable.dataSource" :height="340"
          rowSelection :disabled="formDisabled" :toolbar="true" />
      </a-tab-pane>
      <a-tab-pane tab="日志" key="psPlanOrderLog" :forceRender="true">
        <JVxeTable keep-source resizable ref="psPlanOrderLog" :loading="psPlanOrderLogTable.loading"
          :columns="psPlanOrderLogTable.columns" :dataSource="psPlanOrderLogTable.dataSource"
          :height="340" rowSelection :disabled="formDisabled"
          :toolbar="true" />
      </a-tab-pane>
      <a-tab-pane tab="抵扣明细" key="psPlanOrderDeduction" :forceRender="true">
        <JVxeTable keep-source resizable ref="psPlanOrderDeduction"
          :loading="psPlanOrderDeductionTable.loading" :columns="psPlanOrderDeductionTable.columns"
          :dataSource="psPlanOrderDeductionTable.dataSource" :height="340"
          rowSelection :disabled="formDisabled" :toolbar="true" />
      </a-tab-pane> -->
    </a-tabs>
  </BasicModal>
  <!-- MPS主生产计划列表 -->
  <mpsSelectModel @register="mpsItemRegModal" @getSelectResult="mpsItemhandleSuccess" v-bind="getBindValue"></mpsSelectModel>
</template>

<script lang="ts" setup>
import { ref, computed, unref, reactive } from 'vue';
import { clickExport } from '/@/utils/fileUtils/index'
import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { JVxeTable } from '/@/components/jeecg/JVxeTable';
import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods.ts';
import mpsSelectModel from '/@/views/components/mpsSelectModel.vue';
import {
  formSchema,
  basicinformationFormSchema,
  planParameterFormSchema,
  supplyDemandFormSchema,
  optimizeFormSchema,
  psPlanOrderVersionColumns,
  psPlanOrderItemColumns,
  psPlanOrderResultColumns,
  psPlanOrderOrganizationColumns,
  psPlanOrderLogColumns,
  psPlanOrderDeductionColumns,
} from '../PsPlanOrder.data';
import {
  saveOrUpdate,
  psPlanOrderVersionList,
  psPlanOrderItemList,
  psPlanOrderResultList,
  psPlanOrderOrganizationList,
  psPlanOrderLogList,
  psPlanOrderDeductionList,
  releaseOrder,
} from '../PsPlanOrder.api';
import { VALIDATE_FAILED } from '/@/utils/common/vxeUtils';
import { usePermission } from '/@/hooks/web/usePermission';
const { hasPermission } = usePermission();
import { useMessage } from '/@/hooks/web/useMessage';
const { notification } = useMessage();

// Emits声明
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
const isDetail = ref(false);
const formDisabled = ref(false);
const refKeys = ref([
  'psPlanOrderVersion',
  'psPlanOrderItem',
  'psPlanOrderResult',
  'psPlanOrderOrganization',
  'psPlanOrderLog',
  'psPlanOrderDeduction',
]);
const activeKey = ref('psPlanOrderVersion');
const activeFormKey = ref('formBasicinformation', 'formBasicinformationRef');
const psPlanOrderVersion = ref();
const psPlanOrderItem = ref();
const psPlanOrderResult = ref();
const psPlanOrderOrganization = ref();
const psPlanOrderLog = ref();
const psPlanOrderDeduction = ref();
const formBasicinformationRef = ref();
let activeFilterProp = ref(['']);
const options = [
  {
    value: '',
    label: '全部',
  },
  {
    value: 1,
    label: '采购',
  },
  {
    value: 2,
    label: '委外',
  },
  {
    value: 3,
    label: '自制',
  },
  {
    value: 4,
    label: '虚拟',
  },
];
const tableRefs = {
  psPlanOrderVersion,
  psPlanOrderItem,
  psPlanOrderResult,
  psPlanOrderOrganization,
  psPlanOrderLog,
  psPlanOrderDeduction,
};
const psPlanOrderVersionTable = reactive({
  loading: false,
  dataSource: [],
  columns: psPlanOrderVersionColumns,
});
const psPlanOrderItemTable = reactive({
  loading: false,
  dataSource: [],
  columns: psPlanOrderItemColumns,
});
const psPlanOrderResultTable = reactive({
  loading: false,
  dataSource: [],
  columns: psPlanOrderResultColumns,
});
const psPlanOrderOrganizationTable = reactive({
  loading: false,
  dataSource: [],
  columns: psPlanOrderOrganizationColumns,
});
const psPlanOrderLogTable = reactive({
  loading: false,
  dataSource: [],
  columns: psPlanOrderLogColumns,
});
const psPlanOrderDeductionTable = reactive({
  loading: false,
  dataSource: [],
  columns: psPlanOrderDeductionColumns,
});
//表单配置
const [registerForm, { setFieldsValue: setFieldsValueForm, updateSchema: updateSchemaForm, resetFields, setProps }] = useForm({
  labelWidth: 100,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: {
    span: 6,
  },
});
// 基本信息表单配置
// const [registerBasicinformationForm,{
//   setProps:setPropsBasicinform,
//   validate,
//   setFieldsValue:setFieldsBasicinformValue,
//   getFieldsValue:getFieldsValueBasicinform,
//   updateSchema:updateSchemaBasicinform
// }] = useForm({
//   labelWidth: 100,
//   schemas: basicinformationFormSchema,
//   showActionButtonGroup: false,
//   baseColProps: {
//     span: 6
//   }
// });
// 计划参数表单配置
// const [registerPlanParameterForm,{
//     setFieldsValue:setFieldsPlanParameterValue,
//     getFieldsValue:getFieldsValuePlanParameter,
//     setProps:setPropsPlanParameter,
//     updateSchema:updateSchemaPlanParameter
//   }] = useForm({
//   labelWidth: 100,
//   schemas: planParameterFormSchema,
//   showActionButtonGroup: false,
//   baseColProps: {
//     span: 6
//   }
// });
// 供需 表单配置
// const [registerSupplyDemandForm,{
//       setFieldsValue:setFieldsSupplyDemandValue,
//       getFieldsValue:getFieldsValueSupplyDemand,
//       updateSchema:updateSchemaSupplyDemand,
//       setProps:setPropsSupplyDemand,
//     }] = useForm({
//   labelWidth: 100,
//   schemas: supplyDemandFormSchema,
//   showActionButtonGroup: false,
//   baseColProps: {
//     span: 6
//   }
// });
// 优化 表单配置
// const [registerOptimizeForm,{
//     setFieldsValue:setFieldsOptimizeValue,
//     getFieldsValue:getFieldsValueOptimize,
//     updateSchema:updateSchemaOptimize,
//     setProps:setPropsOptimize,
//   }] = useForm({
//   labelWidth: 100,
//   schemas: optimizeFormSchema,
//   showActionButtonGroup: false,
//   baseColProps: {
//     span: 6
//   }
// });

//方法配置
const [handleChangeTabs, handleSubmit, requestSubTableData, formRef] = useJvxeMethod(
  requestAddOrEdit,
  classifyIntoFormData,
  tableRefs,
  activeKey,
  refKeys
);

//设置标题
const title = computed(() => (unref(isDetail) ? '详情' : !unref(isUpdate) ? '新增' : '编辑'));
// 注册mps筛选框
const getBindValue = Object.assign({}, '');
const [mpsItemRegModal, { openModal: openMpsListModal }] = useModal();
// 计划订单明细 选择的行数据的id
let planOrderItemSelectedRowIds = reactive([]);
async function reset() {
  await resetFields();
  activeKey.value = 'psPlanOrderItem';
  // activeFormKey.value = 'formBasicinformation';
  psPlanOrderVersionTable.dataSource = [];
  psPlanOrderItemTable.dataSource = [];
  psPlanOrderResultTable.dataSource = [];
  psPlanOrderOrganizationTable.dataSource = [];
  psPlanOrderLogTable.dataSource = [];
  psPlanOrderDeductionTable.dataSource = [];
}

function classifyIntoFormData(allValues) {
  let main = Object.assign({}, allValues.formValue);
  return {
    ...main, // 展开
    psPlanOrderVersionList: allValues.tablesValue[0].tableData,
    psPlanOrderItemList: allValues.tablesValue[1].tableData,
    psPlanOrderResultList: allValues.tablesValue[2].tableData,
    psPlanOrderOrganizationList: allValues.tablesValue[3].tableData,
    psPlanOrderLogList: allValues.tablesValue[4].tableData,
    psPlanOrderDeductionList: allValues.tablesValue[5].tableData,
  };
}
// mps List模块
function masterPlanOpen() {
  openMpsListModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}

// 当选择的行变化时触发的事件
function handleSelectRowChange(selectedRowIds) {
  planOrderItemSelectedRowIds = selectedRowIds.selectedRowIds;
}

const displayData = reactive({});
const isProcurementStatus = ref<boolean>(false);
const filterProcurement = (e) => {
  Object.assign(psPlanOrderResultTable, displayData);
  if (e) {
    psPlanOrderResultTable.dataSource = psPlanOrderResultTable.dataSource.filter((item) => {
      return item.supplyType === e;
    });
  }
};
//释放订单
async function handleRelease() {
  if (planOrderItemSelectedRowIds.length > 0) {
    let ids = planOrderItemSelectedRowIds.toString();
    await releaseOrder({ resultIds: ids });

    //关闭弹窗
    closeModal();
    //刷新列表
    emit('success');
  } else {
    notification.warning({
      message: '请先选择数据',
      duration: 3,
    });
  }
}
// mps筛选回写
function mpsItemhandleSuccess(val, values) {
  setFieldsValue({
    // billCode:val[0].mainPlanCode
    masterPlanCode: val[0].mainPlanCode,
    masterPlanId: val[0].id,
  });
}

//表单提交事件
async function requestAddOrEdit(values) {
  try {
    setModalProps({ confirmLoading: true });
    // 处理表格生成的id : row_***
    values.psPlanOrderDeductionList.map((item) => delete item.id);
    values.psPlanOrderItemList.map((item) => delete item.id);
    values.psPlanOrderLogList.map((item) => delete item.id);
    values.psPlanOrderOrganizationList.map((item) => delete item.id);
    values.psPlanOrderResultList.map((item) => delete item.id);
    values.psPlanOrderVersionList.map((item) => delete item.id);
    // 获取基础信息表单数据
    let basicinformData = getFieldsValueBasicinform();
    // 获取计划参数表单数据
    let planParameterData = getFieldsValuePlanParameter();
    // 获取供需表单数据
    let supplyDemandData = getFieldsValueSupplyDemand();
    // 获取优化表单数据
    let optimizeData = getFieldsValueOptimize();
    // 合并数据
    let formValues = Object.assign({}, values, basicinformData, planParameterData, supplyDemandData, optimizeData);

    //提交表单
    await saveOrUpdate(values, isUpdate.value);
    //关闭弹窗
    closeModal();
    //刷新列表
    emit('success');
  } finally {
    setModalProps({
      confirmLoading: false,
    });
  }
}
//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  //重置表单
  await reset();
  setModalProps({
    confirmLoading: false,
    showCancelBtn: data?.showFooter,
    showOkBtn: data?.showFooter,
  });
  isUpdate.value = !!data?.isUpdate;
  isDetail.value = !!data?.isDetail;
  formDisabled.value = !data?.showFooter;
  if (unref(isUpdate)) {
    //表单赋值
    await setFieldsValueForm({
      ...data.record,
    });
    // await setFieldsBasicinformValue({
    //   ...data.record,
    // });
    // await setFieldsPlanParameterValue({
    //   ...data.record,
    // });
    // await setFieldsSupplyDemandValue({
    //   ...data.record,
    // });
    // await setFieldsOptimizeValue({
    //   ...data.record,
    // });
    // requestSubTableData(psPlanOrderVersionList, {
    //   id: data?.record?.id
    // }, psPlanOrderVersionTable)
    requestSubTableData(
      psPlanOrderItemList,
      {
        id: data?.record?.id,
      },
      psPlanOrderItemTable
    );
    requestSubTableData(
      psPlanOrderResultList,
      {
        id: data?.record?.id,
      },
      psPlanOrderResultTable
    );
    setTimeout(() => {
      Object.assign(displayData, psPlanOrderResultTable);
    }, 1000);
    // requestSubTableData(psPlanOrderOrganizationList, {
    //   id: data?.record?.id
    // }, psPlanOrderOrganizationTable)
    // requestSubTableData(psPlanOrderLogList, {
    //   id: data?.record?.id
    // }, psPlanOrderLogTable)
    // requestSubTableData(psPlanOrderDeductionList, {
    //   id: data?.record?.id
    // }, psPlanOrderDeductionTable)
  }
  // 隐藏底部时禁用整个表单
  setProps({
    disabled: !data?.showFooter,
  });
});
</script>

<style lang="less" scoped>
/** 时间和数字输入框样式 */
:deep(.ant-input-number) {
  width: 100%;
}

:deep(.ant-calendar-picker) {
  width: 100%;
}
</style>
